﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Linq;
using System.Web.Mvc;
using Core;
using DataAccess;


namespace CelLibrary
{
    public class Class1
    {
        public static void SmsHandler(SerialPort serialPort)
        {
            string result;
            string resultado = string.Empty;
            int guardado = 0;
            if (serialPort.IsOpen == true)
            {
                var listaFallas = new Repository<Falla>().GetAllRecords();
                serialPort.WriteLine("AT+CMGL=\"REC UNREAD\"\r");
                result = serialPort.ReadLine();
                string[] listaSMS = result.Split(new string[]{"+CMGL: "}, StringSplitOptions.RemoveEmptyEntries);
                foreach (var sms in listaSMS)
                {
                    string[] info1 = sms.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
                    string telefono = info1[2];
                    string[] info2 = info1[3].Split(new char[] { '"' }, StringSplitOptions.RemoveEmptyEntries);
                    result = info2[1];                
                    foreach (var falla in listaFallas)
                    {
                        if (falla.Codigo.Equals(result))
                        {
                            guardado = SaveRecord(telefono, falla.Id);
                            if (guardado != 0)
                            {
                               int mandado = send(serialPort, guardado, falla.Descripcion);
                            }
                        }
                    }
                }
            }
        }
        public static int send(SerialPort serialPort, int idV, string message)
        {
            string cb = char.ConvertFromUtf32(26);
            string result = null;
            Vehiculo car = new Repository<Vehiculo>().GetEntity(idV);
            var user = new Repository<Usuario>().GetEntity(car.IdUsuario.Value);
            var listTelefonos = new Repository<Telefono>().GetAllRecords(u => u.IdUsuario.Equals(user.Id));
            
            if (serialPort.IsOpen == true)
            {
                serialPort.BaseStream.Flush();
                System.Threading.Thread.Sleep(2000);
                serialPort.WriteLine("AT" + (char)(13)); // envio el primer comando at para verificar que este todo ok
                result = serialPort.ReadLine();
                if (result.Equals("OK"))
                {
                    foreach (Telefono phone in listTelefonos)
                    {
                        serialPort.Write("AT+CMGS=\"" + phone + "\"\r\n");
                        serialPort.Write(message + cb);
                        
                    }
                    return 1;

                }
                else
                    return 0;

            }
            else
                return 0;
        }
        public static SerialPort OpenPort(string portName, int portBaud, int portBits, int portRtimeout, int portWtimeout)
        {
            AutoResetEvent receiveNow = new AutoResetEvent(false);
            SerialPort port = new SerialPort();
            port.PortName = portName;
            port.BaudRate = portBaud;
            port.DataBits = portBits;
            port.StopBits = StopBits.One;
            port.Parity = Parity.None;
            port.ReadTimeout = portRtimeout;
            port.WriteTimeout = portWtimeout;
            port.Encoding = Encoding.GetEncoding("iso-8859-1");
           // port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
            try
            {
                port.Open();
                port.DtrEnable = true;
                port.RtsEnable = true;
                return port;
            }
            catch
            {
                return null;
            }

        }
        public static int SaveRecord(string tel, int idFalla)
        {
            //int idV = 0;
            Repository<HistorialFallaVehiculo> listaHistorial = new Repository<HistorialFallaVehiculo>();
            var vehiculo = new Repository<Vehiculo>().GetAllRecords(u => u.Telefono.Equals(tel)).FirstOrDefault();

            HistorialFallaVehiculo historial = new HistorialFallaVehiculo();
            historial.IdFalla = idFalla;
            historial.IdVehiculo = vehiculo.Id;
            historial.Fecha = DateTime.Now;
            try
            {
                listaHistorial.AddEntity(historial);
                listaHistorial.SaveChanges();
                return vehiculo.Id;
            }
            catch
            {
                return 0;
            }
        }
    }
}
